package service

import (
	"awesomeProject/app/model"
	"awesomeProject/app/request"
	"awesomeProject/app/response"
	"awesomeProject/global"
	"awesomeProject/util"
	"fmt"
	"github.com/fatih/structs"
)

type CompanySrv struct{}

func (r *CompanySrv) Pagination(req request.CompanyPagination) response.Resp {
	offset := (req.PageIndex - 1) * req.PageSize
	where := "1=1"
	if req.Keyword != "" {
		where += " AND (`company_name` LIKE '%" + req.Keyword + "%')"
	}
	var total int64
	err := global.Gorm.Model(&model.Company{}).Where(where).Count(&total).Error
	if err != nil {
		return response.ErrQuery
	}
	var companies []model.Company
	err = global.Gorm.Where(where).Offset(offset).Limit(req.PageSize).Find(&companies).Error
	if err != nil {
		return response.ErrQuery
	}
	if len(companies) == 0 {
		return response.OK.WithData(map[string]interface{}{
			"total": 0,
			"list":  companies,
		})
	}

	return response.OK.WithData(map[string]interface{}{
		"total": total,
		"list":  companies,
	})
}

func (r *CompanySrv) FindByID(id uint) (error, model.Company) {
	var company model.Company
	err := global.Gorm.Where("id = ?", id).First(&company).Error

	return err, company
}

func (r *CompanySrv) Update(id uint, req request.CompanyUpdate) response.Resp {
	err, company := r.FindByID(id)
	if err != nil {
		return response.ErrQuery.SetMsg(err.Error())
	}
	if company.ID == 0 {
		return response.ErrRecordNotFound
	}
	updates := structs.Map(req)
	if err = global.Gorm.Model(&company).Updates(updates).Error; err != nil {
		return response.ErrStore.SetMsg(err.Error())
	}
	return response.OK
}

func (r *CompanySrv) Create(company model.CompanyFillAble) response.Resp {
	companyObj := model.Company{
		CompanyFillAble: company,
	}
	if err := global.Gorm.Model(&model.Company{}).Create(&companyObj).Error; err != nil {
		return response.ErrCreate.SetMsg(err.Error())
	}
	return response.OK
}

func (r *CompanySrv) Del(id uint) response.Resp {
	err, company := r.FindByID(id)
	if err != nil {
		return response.ErrQuery.SetMsg(err.Error())
	}
	if company.ID == 0 {
		return response.ErrRecordNotFound
	}
	// 数据删除
	if err := global.Gorm.Unscoped().Delete(&company).Error; err != nil {
		return response.ErrDel.SetMsg(err.Error())
	}
	return response.OK
}

func (r *CompanySrv) All(companyIds []uint, operator model.User) response.Resp {
	var companies []model.Company
	where := "1=1"
	//if companyId != 0 {
	//	where += " and `id`=" + strconv.Itoa(int(companyId))
	//}
	order := "id asc"
	if len(companyIds) > 0 && util.UintsToStr(companyIds,",") != "0" {
		where += fmt.Sprintf(" and `id` in (%s)", util.UintsToStr(companyIds, ","))
		order = "field(`id`," + util.UintsToStr(companyIds, ",") + ")"
	}
	//global.LoggerOut(where)
	err := global.Gorm.Where(where).Order(order).Find(&companies).Error
	if err != nil {
		return response.ErrQuery
	}
	if !operator.SuperAdmin && operator.ID != global.SuperAdminUserID {
		if len(companies) > 1 {
			companies = companies[:2]
			companies[0].ID = global.MainCompanyID
			companies[0].CompanyName = global.MainCompanyName // 主组织

			companies[1].ID = global.OtherCompanyID
			companies[1].CompanyName = global.OtherCompanyName // 其他组织
		} else {
			companies = companies[:1]
			companies[0].ID = global.MainCompanyID
			companies[0].CompanyName = global.MainCompanyName // 主组织
		}
	}
	return response.OK.WithData(companies)
}
